//
//  XGL_GiftListBarView.swift
//  XGamesLive
//
//  Created by ios on 2024/5/23.
//

import UIKit
import SmartCodable
import CollectionKit

struct GiftData: SmartCodable {
    var id: String = ""
    var name: String = ""
    var imgUrl: String = ""
    var price: NSInteger = 0
    var isSelected: Bool = false
    var num: NSInteger = 0
}

class XGL_GiftListBarView: UIView {
    typealias SendGiftAction = (_ selectGift: GiftData)->Void
    
    private var contentView: UIView!
    private var collectionView: CollectionView!
    private var coinText: UILabel!
    private var giftDatas: ArrayDataSource<GiftData> = ArrayDataSource(data: [])
    private var handler: SendGiftAction?
    
    var giftSource: [GiftData] = []{
        didSet{
            self.giftDatas.data = self.giftSource
            self.collectionView.snp.updateConstraints { make in
                make.height.equalTo(ceil(Double(self.giftSource.count) / 4.0) * 100.0)
            }
        }
    }
    var coin: NSInteger = 0{
        didSet{
            self.coinText.text = self.coin.description
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.black.withAlphaComponent(0.15)
        let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.backTouchAction))
        tapGes.delegate = self
        self.addGestureRecognizer(tapGes)
        self.createXglView()
//        self.giftDatas.data = [GiftData(icon: "icon_xgl_gift_1"),GiftData(icon: "icon_gift_2"),GiftData(icon: "icon_gift_3"),GiftData(icon: "icon_gift_4"),GiftData(icon: "icon_gift_5"),GiftData(icon: "icon_gift_6"),GiftData(icon: "icon_gift_7"),GiftData(icon: "icon_gift_8")]
        self.setCollectionData()
        self.getCoinDataRequest()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        self.layoutIfNeeded()
        self.contentView.addCorner(conrners: [.topLeft,.topRight], radius: 12.0)
    }
}

extension XGL_GiftListBarView{
    private func getCoinDataRequest(){
        PanRequestManager<XGL_RequestBaseResponse<CoinData>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .SurplusCoin)) { result in
            switch result{
            case .success(let response):
                if let data = response.resultData {
                    self.coin = NSInteger(data.amount)
                }
                break
            default:
                break
            }
        }
    }
}

extension XGL_GiftListBarView{
    func showGiftPickerView(handler: @escaping SendGiftAction){
        self.handler = handler
        self.layoutIfNeeded()
        self.giftSource = self.giftSource.map({GiftData(id: $0.id,name: $0.name,imgUrl: $0.imgUrl,price: $0.price)})
        self.giftDatas.data = self.giftSource
        UIView.animate(withDuration: 0.25) {
            self.contentView.transform = CGAffineTransform(translationX: 0, y: -self.contentView.bounds.height)
        }
    }
    
    func dismiss(){
        UIView.animate(withDuration: 0.25) {
            self.contentView.transform = .identity
        } completion: { _ in
            self.removeFromSuperview()
        }

    }
}

extension XGL_GiftListBarView{
    @objc private func rightItemAction(){
        
    }
    @objc private func coinItemAction(){
        
    }
    
    @objc private func selecGiftItemAction(sender: UIButton){
        let index = sender.tag - 3000
        var datas = self.giftDatas.data.map({GiftData(id: $0.id,name: $0.name,imgUrl: $0.imgUrl,price: $0.price)})
        datas[index].isSelected = true
        self.giftDatas.data = datas
    }
    @objc private func sendAction(){
        if let item = self.giftDatas.data.first(where: {$0.isSelected}) {
            if self.coin < item.price{
                MXProgressHUD.hudWithText("The balance is insufficient, please recharge")
            }else{
                if let block = self.handler {
                    block(item)
                }
                self.dismiss()
            }
        }
    }
    @objc private func backTouchAction(){
        self.dismiss()
    }
}

extension XGL_GiftListBarView: UIGestureRecognizerDelegate{
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        let touchPoint = touch.location(in: self)
        self.contentView.layoutIfNeeded()
        if self.contentView.frame.contains(touchPoint){
            return false
        }
        
        return true
    }
}

extension XGL_GiftListBarView{
    func setCollectionData(){
        let viewSource = ClosureViewSource(viewUpdater: { [weak self] (view: UIView, data: GiftData, index: Int) in
            guard let `self` = self else { return }
            view.backgroundColor = .clear
            view.removeSubviews()
            let contentView = UIView().then { make in
                make.layerBorderColor = UIColor.hexColor("#83FFE7")
                make.layerBorderWidth = data.isSelected ? 1.0 : 0.0
                make.layerCornerRadius = 12.0
            }
            let iconView = UIImageView().then { make in
                make.loadImageWithUrl(data.imgUrl)
            }
            let coinImageView = UIImageView(image: imageWithName("icon_xgl_gift_coin"))
            let coinLabel = UILabel().then({ make in
                make.textColor = UIColor.white
                make.text = "\(data.price)"
                make.font = UIFont.pingfangSC_Regular(fontSize: 14.0)
            })
            let coinView = UIView()
            let itemButton = UIButton().then { make in
                make.tag = index + 3000
                make.addTarget(self, action: #selector(self.selecGiftItemAction(sender:)), for: .touchUpInside)
            }
            coinView.addSubviews([coinImageView,coinLabel])
            contentView.addSubviews([iconView,coinView,itemButton])
            view.addSubview(contentView)
            coinImageView.snp.makeConstraints { make in
                make.left.centerY.equalToSuperview()
                make.width.height.equalTo(16.0)
            }
            coinLabel.snp.makeConstraints { make in
                make.centerY.equalToSuperview()
                make.left.equalTo(coinImageView.snp.right).offset(5.0)
            }
            coinView.snp.makeConstraints { make in
                make.centerX.equalToSuperview()
                make.top.equalTo(iconView.snp.bottom).offset(7.0)
                make.right.equalTo(coinLabel)
                make.height.equalTo(18.0)
            }
            iconView.snp.makeConstraints { make in
                make.centerX.equalToSuperview()
                make.top.equalTo(10.0)
                make.width.height.equalTo(50.0)
            }
            itemButton.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            contentView.snp.makeConstraints { make in
                make.left.equalTo(6.0)
                make.top.equalTo(9.0)
                make.center.equalToSuperview()
            }
        })
        let sizeSource = { (index: Int, data: GiftData, collectionSize: CGSize) -> CGSize in
            
            return CGSize(width: collectionSize.width / 4.0, height: 110.0)
        }
        let provider = BasicProvider(
            dataSource: self.giftDatas,
            viewSource: viewSource,
            sizeSource: sizeSource
        )
        self.collectionView.provider = provider
    }
}

extension XGL_GiftListBarView{
    private func createXglView(){
        let titleText = UILabel().then { make in
            make.text = "Gift"
            make.font = UIFont.pingfangSC_Semibold(fontSize: 20.0)
            make.textColor = UIColor.hexColor("#80FFE6")
        }
        let rightItem = UIButton().then { make in
            make.setImage(imageWithName("icon_doubt"), for: .normal)
            make.addTarget(self, action: #selector(self.rightItemAction), for: .touchUpInside)
        }
        self.collectionView = CollectionView()
        let coinView = UIImageView(image: imageWithName("icon_xgl_gift_coin"))
        self.coinText = UILabel().then({ make in
            make.textColor = UIColor.white
            make.text = "0"
            make.font = UIFont.pingfangSC_Semibold(fontSize: 14.0)
        })
        let rightIconView = UIImageView(image: imageWithName("icon_more_right_small"))
        let coinButton = UIButton().then { make in
            make.addTarget(self, action: #selector(self.coinItemAction), for: .touchUpInside)
        }
        let sendButton = UIButton().then { make in
            make.setImage(imageWithName("icon_xgl_input_bar_send"), for: .normal)
            make.addTarget(self, action: #selector(self.sendAction), for: .touchUpInside)
        }
        self.contentView = UIView().then({ make in
            make.backgroundColor = UIColor.hexColor("#001310")
        })
        self.contentView.addSubviews([titleText,rightItem,self.collectionView,coinView,coinText,rightIconView,coinButton,sendButton])
        self.addSubview(contentView)
        
        titleText.snp.makeConstraints { make in
            make.left.equalTo(15.0)
            make.top.equalTo(19.0)
        }
        rightItem.snp.makeConstraints { make in
            make.centerY.equalTo(titleText)
            make.right.equalTo(-15.0)
            make.width.height.equalTo(30.0)
        }
        self.collectionView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(titleText.snp.bottom).offset(10.0)
            make.left.equalTo(16.0)
            make.height.equalTo(200.0)
        }
        coinView.snp.makeConstraints { make in
            make.left.equalTo(15.0)
            make.top.equalTo(collectionView.snp.bottom).offset(50.0)
            make.width.height.equalTo(16.0)
        }
        coinText.snp.makeConstraints { make in
            make.centerY.equalTo(coinView)
            make.left.equalTo(coinView.snp.right).offset(5.0)
        }
        rightIconView.snp.makeConstraints { make in
            make.centerY.equalTo(coinView)
            make.left.equalTo(coinText.snp.right).offset(5.0)
            make.width.equalTo(6.0)
            make.height.equalTo(10.0)
        }
        coinButton.snp.makeConstraints { make in
            make.left.equalTo(coinView)
            make.right.equalTo(rightIconView)
            make.height.equalTo(24.0)
            make.centerY.equalTo(coinView)
        }
        sendButton.snp.makeConstraints { make in
            make.centerY.equalTo(coinView)
            make.right.equalTo(-15.0)
            make.width.equalTo(76.0)
            make.height.equalTo(36.0)
        }
        contentView.snp.makeConstraints { make in
            make.width.centerX.equalToSuperview()
            make.top.equalTo(self.snp.bottom)
            make.bottom.equalTo(sendButton.snp.bottom).offset(BottomHeight + 10.0)
        }
       
    }
}
